﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using Common;
using DO.Workflows;
using Microsoft.Practices.EnterpriseLibrary.Data;
using SimpleDataType=Common.SimpleDataType;
using SimpleDataTypeUtil=Common.SimpleDataTypeUtil;

namespace DAL.Workflows
{
    public class StatusDALC
    {
        public static List<Job> GetRunStatus(Guid runID)
        {
            List<Job> jobStatuses=new List<Job>();
            Database db = DatabaseFactory.CreateDatabase("Workflow");
            IDataReader reader = db.ExecuteReader("RunStatusGet", runID);
            while(reader.Read())
            {
                Guid jobID=new Guid(reader["JobID"].ToString());
                Guid componentID=new Guid(reader["ComponentID"].ToString());
                string[] dependencyIDs =
                    StringUtil.Split(reader["Dependencies"] == DBNull.Value
                                         ? string.Empty
                                         : reader["Dependencies"].ToString());
                List<Guid> dependencies=new List<Guid>();
                if(dependencyIDs!=null && dependencyIDs.Length>0)
                {
                    foreach(string dependentID in dependencyIDs)
                    {
                        Guid dependentGuid=new Guid(dependentID);
                        if(!dependencies.Contains(dependentGuid))
                            dependencies.Add(dependentGuid);
                    }
                }
                string componentTypeName = reader["ComponentTypeName"].ToString();
                bool hasError = bool.Parse(reader["HasError"].ToString());
                bool isFirst = bool.Parse(reader["IsFirstJob"].ToString());
                bool isLast = bool.Parse(reader["IsLastJob"].ToString());
                bool cancelled = bool.Parse(reader["Cancelled"].ToString());
                string jobInstructionTypeName = reader["JobInstructionTypeName"].ToString();
                string jobOutputTypeName = reader["JobOutputTypeName"].ToString();
                int jobInstructionID = int.Parse(reader["JobInstructionID"].ToString());
                int jobOutputID = int.Parse(reader["JobOutputID"].ToString());
                ThreadPriority priority = (ThreadPriority)Enum.Parse(typeof(ThreadPriority),reader["Priority"].ToString());
                DateTime? receiveTime = reader["ReceiveTime"] == DBNull.Value
                                            ? new DateTime?()
                                            : DateTime.Parse(reader["ReceiveTime"].ToString());
                DateTime? submissionTime = reader["SubmissionTime"] == DBNull.Value
                                            ? new DateTime?()
                                            : DateTime.Parse(reader["SubmissionTime"].ToString());
                DateTime? startTime = reader["StartTime"] == DBNull.Value
                                            ? new DateTime?()
                                            : DateTime.Parse(reader["StartTime"].ToString());
                DateTime? finishTime = reader["FinishTime"] == DBNull.Value
                                            ? new DateTime?()
                                            : DateTime.Parse(reader["FinishTime"].ToString());
                Job job = new Job
                                          {
                                              JobID = jobID,
                                              RunID = runID,
                                              ComponentID = componentID,
                                              HasError = hasError,
                                              Cancelled = cancelled,
                                              IsFirstJob = isFirst,
                                              IsLastJob = isLast,
                                              JobInstructionID = jobInstructionID,
                                              JobOutputID = jobOutputID,
                                              Priority = priority,
                                              ReceiveTime = receiveTime,
                                              SubmissionTime = submissionTime,
                                              StartTime = startTime,
                                              FinishTime = finishTime
                                          };
                jobStatuses.Add(job);
            }
            reader.Close();
            return jobStatuses;
        }

        public static List<Run> GetWorkflowStatus(Guid workflowID)
        {
            List<Run> runStatuses=new List<Run>();
            Database db = DatabaseFactory.CreateDatabase("Workflow");
            IDataReader reader = db.ExecuteReader("WorkflowStatusGet", workflowID);
            while (reader.Read())
            {
                Guid runID=new Guid(reader["RunID"].ToString());
                Guid triggerInstanceID=new Guid(reader["TriggerInstanceID"].ToString());
                DateTime? submitTime = reader["SubmitTime"] == DBNull.Value
                                           ? new DateTime?()
                                           : DateTime.Parse(reader["SubmitTime"].ToString());
                DateTime? starttTime = reader["StartTime"] == DBNull.Value
                                           ? new DateTime?()
                                           : DateTime.Parse(reader["StartTime"].ToString());
                DateTime? finishTime = reader["FinishTime"] == DBNull.Value
                                           ? new DateTime?()
                                           : DateTime.Parse(reader["FinishTime"].ToString());
                Dictionary<string,GlobalVariable> gVars=new Dictionary<string, GlobalVariable>();
                if(reader["Variables"]!=DBNull.Value)
                {
                    string[] vars = StringUtil.Split(reader["Variables"].ToString());
                    if(vars!=null && vars.Length>0)
                    {
                        foreach(string var in vars)
                        {
                            string[] nameTypeValue = var.Split(new char[] {':'});
                            if(nameTypeValue.Length==3)
                            {
                                GlobalVariable gVar=new GlobalVariable();
                                gVar.VarName = nameTypeValue[0];
                                gVar.DataType = (SimpleDataType) Enum.Parse(typeof (SimpleDataType), nameTypeValue[1]);
                                gVar.VarValue = nameTypeValue[2];
                                gVars.Add(gVar.VarName,gVar);
                            }
                        }
                    }
                }
                Run run = new Run
                              {
                                  RunID = runID,
                                  WorkflowID = workflowID,
                                  SubmitTime = submitTime,
                                  StartTime = starttTime,
                                  FinishTime = finishTime,
                                  Variables = gVars
                              };
                runStatuses.Add(run);
            }
            reader.Close();
            return runStatuses;
        }
    }
}
